import { createSlice } from '@reduxjs/toolkit'
import { api_login, api_getUserInfo } from '@/api/user'

const userStore = createSlice({
  name: 'user',
  initialState: {
    token: '',
    userInfo: {}
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    logOut(state) {
      state.token = ''
      state.userInfo = {}
    }
  }
})

const { setToken, setUserInfo, logOut } = userStore.actions

const login = loginForm => async dispatch => {
  const res = await api_login(loginForm)
  dispatch(setToken(res.data.token))
}

const getUserInfo = () => async dispatch => {
  const res = await api_getUserInfo()
  dispatch(setUserInfo(res.data))
}

export { login, getUserInfo, logOut }

export default userStore.reducer
